<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  @close="removeRightById(scope.row, item1.id)"
                  closable
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- for循环渲染  -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      @close="removeRightById(scope.row, item2.id)"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      @close="removeRightById(scope.row, item3.id)"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRightDailog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="RightDialog" width="50%">
      <el-tree
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        default-expand-all
        show-checkbox
        :default-checked-keys="defkeys"
        @close="setRightDialogClosed"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RightDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialog" width="50%">
      <el-form ref="editRole" :model="editRole" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="editRole.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input v-model="editRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增角色的对话框 -->
    <el-dialog title="新增角色" :visible.sync="addDialog" width="50%">
      <el-form :model="addRoles" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolelist: [],

      // 控制权限对话框显示与隐藏
      RightDialog: false,

      // 控制角色对话框的显示与隐藏
      editDialog: false,

      // 所有权限列表
      rightsList: [],

      treeProps: {
        children: "children",
        label: "authName",
      },

      // 默认选择节点Id的值数组
      defkeys: [],

      // 当前即将分配权限的角色id
      roleId: "",

      // 存取编辑角色的信息
      editRole: [],

      addDialog: false,

      // 存取新增角色信息
      addRoles: {
        roleName: "",
        roleDesc: "",
      },
    };
  },

  created() {
    // 获取所有角色列表
    this.getRolesList();
  },
  methods: {
    // 获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get(`roles`);
      if (res.meta.status != 200)
        return this.$message.error("角色列表获取失败！");
      this.rolelist = res.data;
      console.log(this.rolelist);
    },

    // 删除提示框
    async removeRightById(role, id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmResult);

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${id}`
        );
        if (res.meta.status !== 200) {
          return this.$message.error("用户删除失败！");
        } else {
          this.$message.success("用户删除成功√");
          role.children = res.data;
        }
      }
    },

    async showRightDailog(row) {
      this.roleId = row.id;
      const { data: result } = await this.$http.get(`rights/tree`);

      if (result.meta.status !== 200)
        return this.$message.error("获取权限列表失败！");

      this.rightsList = result.data;
      console.log(this.rightsList);

      this.getLeafKeys(row, this.defkeys);

      this.RightDialog = true;
    },

    // 通过递归，获取角色下所有的三级权限的id，并保存到defkeys中
    getLeafKeys(node, arr) {
      // 若当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      // 递归遍历
      node.children.forEach((element) => {
        this.getLeafKeys(element, arr);
      });
    },

    // 监听分配权限对话框关闭事件
    setRightDialogClosed() {
      this.defkeys = [];
    },

    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      console.log(keys);

      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) return this.$message.error("分配权限失败！");
      this.$message.success("分配权限成功√");
      this.getRolesList();
      this.RightDialog = false;
    },

    // 删除指定角色
    async deleteRoles(id) {
      const { data: res } = await this.$http.delete(`roles/${id}`);
      console.log(id, "ddd");
      if (res.meta.status !== 200) return this.$message.error("删除角色失败！");
      console.log("aaa", res);
      this.RightDialog = false;
      this.getRolesList();
    },

    // 显示角色对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200)
        return this.$message.error("获取角色信息失败！");
      this.editRole = res.data;
      this.editDialog = true;
    },

    // 点击确定修改角色信息
    async updateRole() {
      const { data: res } = await this.$http.put(
        `roles/${this.editRole.roleId}`,
        {
          roleName: this.editRole.roleName,
          roleDesc: this.editRole.roleDesc,
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("更新角色信息失败！");
      this.editDialog = false;
      this.getRolesList();
    },

    // 显示添加角色对话框
    showRoleDialog() {
      this.addDialog = true;
    },

    // 添加新的角色
    async addRole() {
      const { data: res } = await this.$http.post(`roles`, this.addRoles);
      console.log(res);
      if (res.meta.status !== 201) return this.$message.error("新增角色信息失败！");
      this.$message.success("新增角色成功√");
      this.addDialog = false;
      this.getRolesList();
    },

    // 
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>